package cn.lg.soar.database.config;

import cn.lg.soar.common.data.msg.I18n;
import cn.lg.soar.common.exceptions.BaseBException;
import cn.lg.soar.common.exceptions.ParameterException;
import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.util.data.StringUtil;
import cn.lg.soar.core.handler.ex.ErrorResult;
import cn.lg.soar.core.handler.ex.SoarExceptionHandler;
import cn.lg.soar.database.query.exception.SoarQueryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.BadSqlGrammarException;

/**
 * 全局拦截异常处理异常
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Configuration
public class DatabaseExceptionHandleConfig extends SoarExceptionHandler {

    protected static final Logger LOGGER = LoggerFactory.getLogger(DatabaseExceptionHandleConfig.class);

    static {
        SoarExceptionHandler.register(SoarQueryException.class, exception -> {
            SoarQueryException e = (SoarQueryException) exception;
            return new ErrorResult(400, HttpResult.fail(new ParameterException(104, I18n.build(e.getMessage()), (Object[]) e.getParams())));
        });

        SoarExceptionHandler.register(DuplicateKeyException.class, exception -> {
            DuplicateKeyException e = (DuplicateKeyException) exception;
            String messageArgs = null;
            try {
                messageArgs = e.getCause().getMessage()
                        .replaceAll("Duplicate entry '", StringUtil.EMPTY)
                        .replaceAll("' for key .*", StringUtil.EMPTY);
            }catch (Exception ex){
                LOGGER.error("数据重复异常信息解析失败", ex);
            }
            return new ErrorResult(400, HttpResult.fail(new ParameterException(102, I18n.build("{0} 已存在"), messageArgs)));
        });

        SoarExceptionHandler.register(DataIntegrityViolationException.class, exception -> {
            DataIntegrityViolationException e = (DataIntegrityViolationException) exception;
            String message = e.getCause().getMessage();
            if (message.contains("' doesn't have a default value")) {
                return new ErrorResult(400, HttpResult.fail(
                        new ParameterException(
                                101,
                                I18n.build("{0} 必需设置一个值"),
                                message.substring(7, message.length() - 30)
                        )
                ));
            }
            if (message.contains("Data truncation: Data too long for column '")) {
                return new ErrorResult(400, HttpResult.fail(
                        new ParameterException(
                                103,
                                I18n.build("{0} 字数超出"),
                                message.substring(43, message.indexOf("'", 43))
                        )
                ));
            }
            return new ErrorResult(400, HttpResult.fail(new ParameterException(I18n.build("数据不完整"))));
        });

        SoarExceptionHandler.register(BadSqlGrammarException.class, exception -> {
            BadSqlGrammarException e = (BadSqlGrammarException) exception;
            String message = e.getCause().getMessage();
            if (message.contains("Unknown column '")) {
                message = message.replace("Unknown column '", "");
                int i = message.indexOf("'");
                return new ErrorResult(500, HttpResult.fail(
                        new BaseBException(4, I18n.build("未知字段“{0}”"), message.substring(0, i))
                ));
            }
            return new ErrorResult(500, HttpResult.fail(new BaseBException(4, I18n.build("sql语法错误"))));
        });

    }

    /**
     * 初始化
     */
    public static void init() {}
}
